package top.dimples.resovler;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.dimples.common.Consts;
import top.dimples.common.JWTUser;
import top.dimples.model.UserProfile;
import top.dimples.service.UserProfileService;
import top.dimples.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author Dimples_YJ
 * @date 2021/12/7
 */
@Component
public class CustomArugsResovler implements HandlerMethodArgumentResolver {

    @Autowired
    private UserProfileService userProfileService;


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(JWTUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Consts.AUTHORIZATION);
        HashMap<String, String> map = JwtUtil.parseToken(token);
        String uId = map.get("uId");
        String roles = map.get("roles");
        UserProfile userProfile = userProfileService.getById(uId);
        JWTUser jwtUser = new JWTUser();
        BeanUtil.copyProperties(userProfile,jwtUser);
        jwtUser.setRoles(roles);
        return jwtUser;
    }
}
